package com.szcinda.service.dto.vehicle;

import com.szcinda.repository.Goods;
import com.szcinda.repository.GoodsRepository;
import com.szcinda.service.SnowFlakeFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {
    private final GoodsRepository goodsRepository;
    private final SnowFlakeFactory snowFlakeFactory;

    public GoodsServiceImpl(GoodsRepository goodsRepository) {
        this.goodsRepository = goodsRepository;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public void create(CreateGoodsDto createGoodsDto) {
        Goods goods = goodsRepository.findByName(createGoodsDto.getName());
        Assert.isTrue(goods == null, "存在相同货物品名的记录");
        goods = new Goods();
        BeanUtils.copyProperties(createGoodsDto, goods);
        goods.setId(snowFlakeFactory.nextId("VE"));
        goodsRepository.save(goods);
    }

    @Override
    public void delete(String id, String userId) {
        goodsRepository.delete(id);
    }

    @Override
    public List<Goods> findAll() {
        return goodsRepository.findAll();
    }

    @Override
    public void batchCreate(List<GoodsImportDto> importDatas, String opId) {
        List<Goods> goods = goodsRepository.findAll();
        for (GoodsImportDto importDto : importDatas) {
            boolean b = goods.stream().noneMatch(vehicle -> vehicle.getName().equals(importDto.getName()));
            if (b) {
                Goods saveGoods = new Goods();
                BeanUtils.copyProperties(importDto, saveGoods);
                saveGoods.setId(snowFlakeFactory.nextId("GS"));
                goodsRepository.save(saveGoods);
            }
        }
    }
}
